<!-- 分段控件 -->
<template>
	<view class="pb-subsection pb-flex-row">
		<view class="item" :style="itemStyle" :class="{'active':index == selectIndex}" v-for="(item,index) in list"
			:key="index" @click="onClick(item,index)">
			<slot>
				<text>{{item[keyName]}}</text>
			</slot>
		</view>
	</view>
</template>

<script>
	export default {
		name: "pb-subsection",
		props: {
			list: {
				type: Array,
				default: () => [],
				require: true
			},
			keyName: {
				type: String,
				default: "name",
				require: false
			},
			defaultIndex: {
				type: [String, Number],
				default: 0,
				require: false
			},
			itemStyle: {
				type: String,
				default: "",
				require: false
			}
		},
		data() {
			return {
				selectIndex: 0,
			};
		},
		watch: {
			defaultIndex: {
				handler(newVal) {
					this.selectIndex = newVal
					if (this.list && this.list.length <= this.defaultIndex) {
						this.selectIndex = 0
					}
				}
			}
		},
		methods: {
			onClick(item, index) {
				item.index = index
				this.selectIndex = index
				console.log('【pb-subsection】onClick=>' + JSON.stringify(item))
				this.$emit('change', item)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.pb-subsection {
		padding: 24rpx 32rpx 12rpx 32rpx;
		background-color: white;

		.item {
			font-size: 28rpx;
			font-weight: 500;
			border: 1rpx $uni-color-primary solid;
			border-right: none;
			background-color: white;
			color: $uni-color-primary;
			padding: 8rpx 12rpx;

			&:first-child {
				border-radius: 8rpx 0 0 8rpx;
			}

			&:last-child {
				border-radius: 0 8rpx 8rpx 0;
				border-right: 1rpx $uni-color-primary solid;
			}

			&.active {
				color: white;
				background-color: $uni-color-primary;
			}
		}
	}
</style>